import xlrd

def createinverse():
    """
    the GBKPY file is not good
    for there are some code error and format error
    so write another function which read the GBKPY.xls file
    """
    f = open("GBKPY.txt")
    lines = f.readlines()
    f.close()

    inversedic = {}
    f = open("inverseGBKPY.txt","w")
    for l in lines:
        if l.endswith("\n"):
            l = l[0:len(l)-1]            
        sp = l.split(" ")
        pinyin = sp[0]
        words = sp[1]
        for i in range(len(words)/3):
            word = words[i*3:(i+1)*3]
            if not inversedic.has_key(word):
                inversedic[word] = []
            inversedic[word].append(pinyin)
    for k in inversedic.keys():
        tmpstr = k
        for p in inversedic[k]:
            tmpstr += ","+p
        #print>>f,k+str(inversedic[k])
        print>>f,tmpstr

    f.close()

def createxls():
    """
    the code get from xls is unicode?
    do not need to get one chinese char by get 3 byte
    """
    fname = "GBKPY.xls"
    bk = xlrd.open_workbook(fname)
    sh = bk.sheet_by_name("Sheet1")
    nrows = sh.nrows

    inversedic = {}
    f = open("inverseGBKPYxls.txt","w")
    for i in range(nrows):
        pinyin = sh.cell_value(i,0)
        words = sh.cell_value(i,1)
        for i in range(len(words)):
            word = words[i]
            if not inversedic.has_key(word):
                inversedic[word] = []
            inversedic[word].append(pinyin)
            
    for k in inversedic.keys():
        tmpstr = k
        for p in inversedic[k]:
            tmpstr += ","+p
        print>>f,tmpstr.encode("utf-8")

    f.close()
    

if __name__ == "__main__":
    #createinverse()
    createxls()
